<?php

namespace Modules\Admin\Http\Controllers;

use App\Admin;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
use Illuminate\Routing\Controller;
use Modules\Admin\Http\Requests\AddAdminUserRequest;
use Spatie\Permission\Models\Role;

class AdminUserController extends Controller
{
    /**
     * Display a listing of the resource.
     * @return Response
     */
    public function index()
    {
    	//$admins= Admin::paginate(10);
		$admins = Admin::where('name','!=','admin')->paginate(10);
		return view('admin::adminuser.index',compact ('admins'));
    }

    /**
     * Show the form for creating a new resource.
     * @return Response
     */
    public function create()
    {
        return view('admin::create');
    }

    /**
     * Store a newly created resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function store(AddAdminUserRequest $request)
    {
		$post = $request->all();
		$post['password'] = bcrypt($post['password']);
		Admin::create($post);
		//设置闪存并返回
		session()->flash('success','用户添加成功');
		return redirect()->route('adminuser.index');
    }

    /**
     * Show the specified resource.
     * @return Response
     */
    public function show()
    {
        return view('admin::show');
    }

    /**
     * Show the form for editing the specified resource.
     * @return Response
     */
    public function edit()
    {
        return view('admin::edit');
    }

    /**
     * Update the specified resource in storage.
     * @param  Request $request
     * @return Response
     */
    public function update(AddAdminUserRequest $request,$id)
    {
    	//dd ($id);
    	$admin = Admin::find($id);
    	$admin->name = $request->input ('name');
    	$admin->nickname = $request->input ('nickname');
    	if ($request->input ('password')){
    		$admin->password = bcrypt ($request->input ('password'));
		}
		$admin->save ();
    	session ()->flash ('success','用户修改成功');
    	return redirect ()->route ('adminuser.index');
    }

    /**
     * Remove the specified resource from storage.
     * @return Response
     */
    public function destroy($id)
    {
		Admin::destroy ($id);
		session ()->flash ('success','用户删除成功');
		return back ();
    }
    public function showRole($adminid){
    	$admin = Admin::find($adminid);
    	$roles = Role::where('name','!=','zhanzhang')->get();
    	return view ('admin::adminuser.showRole',compact ('admin','roles'));
	}
	public function assignRole(Request $request,$adminid){
		if (!$request->input ('name')){
			session ()->flash ('danger','最少选择一个角色');
			return back ();
		}
		$admin = Admin::find($adminid);
		$admin->syncRoles ($request->input ('name'));
		session ()->flash ('success','角色添加成功');
		return back();
	}
}
